package org.smoozik.services.sound;

import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiEvent;
import javax.sound.midi.MidiMessage;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.Synthesizer;
import javax.sound.midi.Track;

public class MidiCreator {
	int channel_ = 0;
	Sequence sequence_;

	public MidiCreator() throws InvalidMidiDataException {
		sequence_ = createSequence();
		 Track track = sequence_.createTrack();
//		sequence_.createTrack();

		 MidiMessage message = addNote(60);
		 MidiEvent event = new MidiEvent(message, 400);
		 track.add(event);

		// message = addNote(60);
		// event = new MidiEvent(message, 40);
		// track.add(event);
	}

	public Sequence createSequence() throws InvalidMidiDataException {
		Sequence mySeq;
		mySeq = new Sequence(Sequence.PPQ, 10);

		return mySeq;
	}

	public Track createTrack(Sequence sequence) {
		return sequence.createTrack();
	}

	public MidiMessage addNote(int note) throws InvalidMidiDataException {
		ShortMessage message = new ShortMessage(ShortMessage.NOTE_ON, channel_,
				note, 0);

		return message;
	}

	public MidiMessage stopNote(int note) throws InvalidMidiDataException {
		ShortMessage message = new ShortMessage(ShortMessage.NOTE_OFF,
				channel_, note, 0);

		return message;
	}

	public Sequence getSequence() {
		return sequence_;
	}

	public void setSequence(Sequence sequence_) {
		this.sequence_ = sequence_;
	}

	public static void main(String[] args) throws InvalidMidiDataException,
			MidiUnavailableException {
		MidiCreator mc = new MidiCreator();
		Sequence sequence = mc.getSequence();

		Synthesizer synthesizer = MidiSystem.getSynthesizer();
		synthesizer.open();

		Sequencer sequencer = MidiSystem.getSequencer();
		sequencer.setSequence(sequence);
		sequencer.open();
		sequencer.start();
		sequencer.close();
	}

}
